package com.hailiao.beidou.message.data.db.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.hailiao.beidou.message.data.db.DB
import com.hailiao.beidou.message.data.db.entity.ContactEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface ContactDao {

    // 查询
    @Query("SELECT * FROM contact_table ORDER BY `pinyin`, `number` ASC")
    fun query(): Flow<List<ContactEntity>>

    // 模糊查询
    @Query("SELECT * FROM contact_table WHERE name LIKE '%'||:value||'%' OR number LIKE '%'||:value||'%' OR note LIKE '%'||:value||'%' OR pinyin LIKE '%'||:value||'%' ORDER BY name ASC")
    suspend fun susQueryBlur(value: String): List<ContactEntity>

    // 卡号模糊查询
    @Query("SELECT * FROM contact_table WHERE number LIKE '%'||:number||'%'")
    suspend fun susQueryLike(number: String): List<ContactEntity>

    // 查询
    @Query("SELECT * FROM contact_table WHERE number = :number")
    suspend fun susQuery(number: String): ContactEntity?

    // 查询
    @Query("SELECT * FROM contact_table WHERE number = :number")
    fun query(number: String): Flow<ContactEntity?>

    // 查询
    @Query("SELECT * FROM contact_table WHERE id = :id")
    suspend fun susQuery(id: Long): ContactEntity?

    // 查询
    @Query("SELECT * FROM contact_table WHERE id = :id")
    fun query(id: Long): Flow<ContactEntity?>

    // 插入
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(info: ContactEntity): Long

    // 修改
    @Update(onConflict = OnConflictStrategy.REPLACE)
    suspend fun update(info: ContactEntity)

    // 删除
    @Delete
    suspend fun delete(info: ContactEntity)

    // 删除
    @Transaction
    suspend fun deleteWithChatAndMessage(info: ContactEntity) {
        delete(info)
        DB.instant.chatDao().delete(info.number)
        DB.instant.messageDao().delete(info.number)
    }
}